<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-08 14:59:26
 * @Last Modified time: 2022-12-05 17:15:03
 */

namespace frank\middleware;


use app\Request;
use frank\middleware\MiddlewareInterface;
use think\facade\Config;
use think\Response;

/**
 * 跨域中间件
 * Class AllowOriginMiddleware
 * @package frank\middleware
 */
class AllowOriginMiddleware implements MiddlewareInterface
{

    /**
     * 允许跨域的域名
     * @var string
     */
    protected $cookieDomain;

    /**
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        $this->cookieDomain = Config::get('cookie.domain', '');
        $header = Config::get('cookie.header');
        $origin = $request->header('origin');
        if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))){
            $header['Access-Control-Allow-Origin'] = $origin;
        }
        if ($request->method(true) == 'OPTIONS') {
            $response = Response::create('ok')->code(200)->header($header);
        } else {
            $response = $next($request)->code(200)->header($header);
        }
        return $response;
    }
}
